package com.huanqiu.mylib.util;

import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

import de.undercouch.bson4jackson.BsonFactory;

public class BsonUtil {

    private static final ObjectMapper sMapper = new ObjectMapper(new BsonFactory());

    public static byte[] toBson(Object obj) {
        // ObjectMapper mapper = new ObjectMapper(new BsonFactory());
        ObjectMapper mapper = sMapper;
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        try {
            mapper.writeValue(baos, obj);
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
        return baos.toByteArray();
    }

    public static <T> T toObject(byte[] data, Class<T> clazz) {
        // ObjectMapper mapper = new ObjectMapper(new BsonFactory());
        ObjectMapper mapper = sMapper;
        ByteArrayInputStream bais = new ByteArrayInputStream(data);
        T obj;
        try {
            obj = mapper.readValue(bais, clazz);
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
        return obj;
    }

}
